package com.morehair.service.wx.impl;

import com.github.pagehelper.PageHelper;
import com.morehair.bean.bo.wx.ListOfGoodsBo;
import com.morehair.bean.pojo.*;
import com.morehair.bean.vo.admin.GoodsDataVo;
import com.morehair.bean.vo.admin.GoodsVo;
import com.morehair.bean.vo.wx.*;
import com.morehair.mapper.*;
import com.morehair.service.wx.WxGoodsService;
import com.morehair.utils.GetNowUser;
import com.morehair.utils.StringOfGoodsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Description:
 * Date: 2021/6/9
 * Time: 10:14
 * author: zhang wei
 */

@Service
@Transactional
public class WxGoodsServiceImpl implements WxGoodsService {

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    AttributeOfGoodsMapper attributeOfGoodsMapper;

    @Autowired
    SpecificationOfGoodsMapper specificationOfGoodsMapper;

    @Autowired
    GrouponRulesMapper grouponRulesMapper;

    @Autowired
    IssueMapper issueMapper;

    @Autowired
    CollectMapper collectMapper;

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    BrandMapper brandMapper;

    @Autowired
    ProductOfGoodsMapper productOfGoodsMapper;


    public static List<String> stringToList(String preStr) {
        List<String> list = new ArrayList<>();
        if (preStr.length() > 4) {
            String[] strArr = preStr.substring(1, preStr.length() - 1).split(", ");
            // 数组转化为List
            for (String str : strArr) {
                list.add(str.substring(1, str.length() - 1));
            }
        }
        return list;
    }


    @Override
    public TotalOfGoodsVo totalOfGoods() {
        List<Goods> allGoods = goodsMapper.selectAllGoods();
        int size = allGoods.size();
        TotalOfGoodsVo totalOfGoodsVo = new TotalOfGoodsVo();
        totalOfGoodsVo.setGoodsCount(size);
        return totalOfGoodsVo;
    }

    @Override
    public CategoryInHomeVo lookCategory(Integer id) {

        Category category = categoryMapper.selectByPrimaryKey(id);
        Integer pid = category.getPid();
        CategoryInHomeVo categoryInHomeVo;
        if (pid == 0) {
            CategoryInHomeVo.ParentCategory parentCategory = categoryMapper.selectByPidInHomeCategory(id);
            List<CategoryInHomeVo.BrotherCategory> brotherCategoryList = categoryMapper.selectByPidForBroToList(id);
            CategoryInHomeVo.BrotherCategory[] array = new CategoryInHomeVo.BrotherCategory[brotherCategoryList.size()];
            CategoryInHomeVo.BrotherCategory[] brotherCategories = brotherCategoryList.toArray(array);
            Integer id1 = brotherCategories[0].getId();
            CategoryInHomeVo.CurrentCategory currentCategory = categoryMapper.selectByIdForCurrent(id1);
            categoryInHomeVo = new CategoryInHomeVo(currentCategory, brotherCategoryList, parentCategory);
        } else {
            CategoryInHomeVo.CurrentCategory currentCategory = categoryMapper.selectByIdForCurrent(id);
            Integer pid1 = currentCategory.getPid();
            CategoryInHomeVo.ParentCategory parentCategory = categoryMapper.selectByPidInHomeCategory(pid1);
            List<CategoryInHomeVo.BrotherCategory> brotherCategoryList = categoryMapper.selectByPidForBroToList(pid1);
            categoryInHomeVo = new CategoryInHomeVo(currentCategory, brotherCategoryList, parentCategory);
        }

        return categoryInHomeVo;
    }


    @Override
    public DetailOfGoodsDataVo getGoodsDetail(Integer id) {

        /**
         * attribute
         */
        List<AttributeOfGoods> attribute = attributeOfGoodsMapper.selectByGoodsId(id);


        /**
         * specificationList
         */
        List<DetailOfGoodsDataVo.SpecificationList> specificationLists = new ArrayList<>();

        List<SpecificationOfGoods> specificationOfGoodsList = specificationOfGoodsMapper.selectByGoodsId(id);

        List<String> names = new ArrayList<>();
        for (SpecificationOfGoods specificationOfGoods : specificationOfGoodsList) {
            //
            String name = specificationOfGoods.getSpecification();
            if (names.size() == 0) names.add(name);
            boolean tag = true;
            for (String s : names) {
                if (s.equals(name)) {
                    tag = true;
                    break;
                } else {
                    tag = false;
                    continue;
                }
            }
            if (tag == false) {
                names.add(name);
            }
        }
        for (String name : names) {
            DetailOfGoodsDataVo.SpecificationList specificationList = new DetailOfGoodsDataVo.SpecificationList();
            specificationList.setName(name);
            List<SpecificationOfGoods> specificationOfGoods = new ArrayList<>();
            for (SpecificationOfGoods ofGoods : specificationOfGoodsList) {
                if (ofGoods.getSpecification().equals(name)) {
                    specificationOfGoods.add(ofGoods);
                }
            }
            specificationList.setValueList(specificationOfGoods);
            specificationLists.add(specificationList);
        }


        /**
         * groupon
         */
        List<GrouponRules> grouponRulesList = grouponRulesMapper.selectByGoodsId(id);


        /**
         * issue
         */
        List<Issue> issueList = issueMapper.selectAll();

        /**
         * userHasCollect
         */
        User user = GetNowUser.getUser();
        Integer userId = user.getId();
        int isCollect;
        int num = collectMapper.selectByUserIdAndGoodsId(userId, id);
        if (num == 0) {
            isCollect = 0;
        } else {
            isCollect = 1;
        }

        /**
         * shareImage
         */
        Goods goods = goodsMapper.selectShareImg(id);
        String shareUrl = goods.getShareUrl();

        /**
         * comment
         */
        DetailOfGoodsDataVo.Comment comment = new DetailOfGoodsDataVo.Comment();
        int commentTotal = commentMapper.selectByGoodsIdForAll(id);
        comment.setCount(commentTotal);

        List<Comment> commentList = commentMapper.selectForTwoByGoodsId(id);
        List<CommentDataVo> commentDataVos = new ArrayList<>();
        for (Comment com : commentList) {
            CommentDataVo commentDataVo = new CommentDataVo();

            Integer comUserId = com.getUserId();
            User userForCom = userMapper.selectByPrimaryKey(comUserId);


            commentDataVo.setId(com.getId());
            commentDataVo.setContent(com.getContent());

            String picUrls = com.getPicUrls();
            List<String> strings = stringToList(picUrls);
            commentDataVo.setPicList(strings);//待定

            commentDataVo.setAvatar(userForCom.getAvatar());
            commentDataVo.setAddTime(com.getAddTime());
            commentDataVo.setNickname(userForCom.getNickname());

            commentDataVos.add(commentDataVo);
        }
        comment.setData(commentDataVos);


        /**
         * brand
         */
        Goods goodsForBrand = goodsMapper.selectByPrimaryKey(id);
        Integer brandId = goodsForBrand.getBrandId();
        Brand brand = brandMapper.selectByPrimaryKey(brandId);


        /**
         * productList
         */
        List<ProductOfGoods> productOfGoodsList = productOfGoodsMapper.selectByGoodsId(id);
        List<DetailOfGoodsDataVo.ProductList> productLists = new ArrayList<>();
        for (ProductOfGoods productOfGoods : productOfGoodsList) {
            DetailOfGoodsDataVo.ProductList productList = new DetailOfGoodsDataVo.ProductList();

            productList.setId(productOfGoods.getId());
            productList.setGoodsId(id);

            //
            String getSpecifications = productOfGoods.getSpecifications();
            String substring = getSpecifications.substring(1, getSpecifications.length() - 1);

            String[] arrayOfSubstring = substring.split(", ");

            List<String> strings = new ArrayList<>();
            for (String s : arrayOfSubstring) {
                String s1 = s.substring(1, s.length() - 1);
                strings.add(s1);
            }

            // List<String> stringList = Arrays.asList(arrayOfSubstring);

            productList.setSpecifications(strings);
            //
            productList.setPrice(productOfGoods.getPrice());
            productList.setNumber(productOfGoods.getNumber());
            productList.setUrl(productOfGoods.getUrl());
            productList.setAddTime(productOfGoods.getAddTime());
            productList.setUpdateTime(productOfGoods.getUpdateTime());
            productList.setDeleted(productOfGoods.getDeleted());

            productLists.add(productList);
        }


        /**
         * info
         */
        Goods goodsInfo = goodsMapper.selectByPrimaryKey(id);
        String gallery = goodsInfo.getGallery();
        List<String> strings = StringOfGoodsUtil.stringToList(gallery);
        GoodsVo goodsVo = goodsMapper.selectToGoodsVo(id);
        goodsVo.setGallery(strings);

        /**
         * 结果
         */
        DetailOfGoodsDataVo detailOfGoodsDataVo = new DetailOfGoodsDataVo(
                specificationLists,
                grouponRulesList, issueList, isCollect, shareUrl, comment, attribute, brand, productLists, goodsVo);
        return detailOfGoodsDataVo;
    }

    @Override
    public RelatedDataVo getRelated(Integer id) {
        List<GoodsOfFloorVo> goodsOfFloorVos = goodsMapper.selectByRandomExceptId(id);
        RelatedDataVo relatedDataVo = new RelatedDataVo();
        relatedDataVo.setGoodsList(goodsOfFloorVos);
        return relatedDataVo;
    }

    @Override
    public ListOfGoodsVo getList(ListOfGoodsBo listOfGoodsBo) {
        ListOfGoodsVo listOfGoodsVo = new ListOfGoodsVo();

        /**
         * 分页
         */
        PageHelper.startPage(listOfGoodsBo.getPage(), listOfGoodsBo.getSize());

        /**
         * 排序
         */
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria goodscriteria = goodsExample.createCriteria();
        goodscriteria.andDeletedEqualTo(false);
        if (listOfGoodsBo.getSort() != null && listOfGoodsBo.getOrder() != null) {
            // sort and order 排序
            goodsExample.setOrderByClause(listOfGoodsBo.getSort() + " " + listOfGoodsBo.getOrder());
        }

        /**
         *搜索 keyword
         */
        String keyword = listOfGoodsBo.getKeyword();
        if (keyword != null && !"".equals(keyword)) {
            // 搜索判断 的 list 判断keyword
            goodscriteria.andNameLike("%" + keyword + "%");
            // goodsList
            List<Goods> goods = goodsMapper.selectByExample(goodsExample);
            List<GoodsOfFloorVo> goodsListBeans = new ArrayList<>();
            for (Goods good : goods) {
                GoodsOfFloorVo goodsListBean = new GoodsOfFloorVo(good.getId(), good.getName(), good.getBrief(), good.getPicUrl(), good.getIsNew(), good.getIsHot(), good.getCounterPrice(), good.getRetailPrice());
                goodsListBeans.add(goodsListBean);
            }
            listOfGoodsVo.setGoodsList(goodsListBeans);
            // count
            int countInSearch = goodsListBeans.size();
            listOfGoodsVo.setCount(countInSearch);

            // filterCategoryList 应该是搜索时 才有效 搜索商品名对应的二级商品类
            Goods goodsToGetCategoryId = goods.get(0);

            Integer getCategoryId = goodsToGetCategoryId.getCategoryId();

            Category category = categoryMapper.selectByPrimaryKey(getCategoryId);
            Category singleCategory = new Category(
                    category.getId(),
                    category.getName(),
                    category.getKeywords(),
                    category.getDesc(),
                    category.getPid(),
                    category.getIconUrl(),
                    category.getPicUrl(),
                    category.getLevel(),
                    category.getSortOrder(),
                    category.getAddTime(),
                    category.getUpdateTime(),
                    category.getDeleted()
            );

            List<Category> categoryList = new ArrayList<>();
            categoryList.add(singleCategory);

            listOfGoodsVo.setFilterCategoryList(categoryList);

            return listOfGoodsVo;
        }
        /**
         * 顶部一级目录
         */
        Integer categoryId = listOfGoodsBo.getCategoryId();

        if (listOfGoodsBo.getBrandId() == null && categoryId != 0 && categoryId != null && listOfGoodsBo.getIsNew() == null && listOfGoodsBo.getIsHot() == null) {
            // goodsList
            goodscriteria.andCategoryIdEqualTo(categoryId);
            List<Goods> goods = goodsMapper.selectByExample(goodsExample);
            List<GoodsOfFloorVo> topicGoodsList = new ArrayList<>();
            for (Goods good : goods) {
                GoodsOfFloorVo goodsListBean = new GoodsOfFloorVo(good.getId(), good.getName(), good.getBrief(), good.getPicUrl(), good.getIsNew(), good.getIsHot(), good.getCounterPrice(), good.getRetailPrice());
                topicGoodsList.add(goodsListBean);
            }
            int count = (int) goodsMapper.countByExample(goodsExample);
            listOfGoodsVo.setCount(count);
            listOfGoodsVo.setGoodsList(topicGoodsList);

            return listOfGoodsVo;
        }


        /**
         * 人气
         */
        Boolean isHot = listOfGoodsBo.getIsHot();
        if (isHot != null && !"".equals(isHot)) {
            goodscriteria.andIsHotEqualTo(isHot);
            List<Goods> goodsForHot = goodsMapper.selectByExample(goodsExample);
            List<GoodsOfFloorVo> hotGoodsList = new ArrayList<>();
            for (Goods good : goodsForHot) {
                GoodsOfFloorVo goodsListBean = new GoodsOfFloorVo(good.getId(), good.getName(), good.getBrief(), good.getPicUrl(), good.getIsNew(), good.getIsHot(), good.getCounterPrice(), good.getRetailPrice());
                hotGoodsList.add(goodsListBean);
            }
            listOfGoodsVo.setGoodsList(hotGoodsList);

            // count
            int countIsHot = hotGoodsList.size();
            listOfGoodsVo.setCount(countIsHot);

            return listOfGoodsVo;


        }


        /**
         * 新品
         */
        Boolean isNew = listOfGoodsBo.getIsNew();
        if (isNew != null && !"".equals(isNew)) {
            goodscriteria.andIsNewEqualTo(isNew);
            List<Goods> goodsForNew = goodsMapper.selectByExample(goodsExample);
            List<GoodsOfFloorVo> newGoodsList = new ArrayList<>();
            for (Goods good : goodsForNew) {
                GoodsOfFloorVo goodsListBean = new GoodsOfFloorVo(good.getId(), good.getName(), good.getBrief(), good.getPicUrl(), good.getIsNew(), good.getIsHot(), good.getCounterPrice(), good.getRetailPrice());
                newGoodsList.add(goodsListBean);
            }
            listOfGoodsVo.setGoodsList(newGoodsList);

            // count
            int countIsNew = newGoodsList.size();
            listOfGoodsVo.setCount(countIsNew);

            return listOfGoodsVo;

        }


        /**
         * brand
         */
        Integer brandId = listOfGoodsBo.getBrandId();
        if (brandId != 0 && brandId != null) {
            // goodsList
            goodscriteria.andBrandIdEqualTo(brandId);
            List<Goods> goodsInBrand = goodsMapper.selectByExample(goodsExample);
            List<GoodsOfFloorVo> goodsInBrandList = new ArrayList<>();
            for (Goods good : goodsInBrand) {
                GoodsOfFloorVo goodsListBean = new GoodsOfFloorVo(good.getId(), good.getName(), good.getBrief(), good.getPicUrl(), good.getIsNew(), good.getIsHot(), good.getCounterPrice(), good.getRetailPrice());
                goodsInBrandList.add(goodsListBean);
            }
            int countGoodsInBrand = (int) goodsMapper.countByExample(goodsExample);
            listOfGoodsVo.setCount(countGoodsInBrand);
            listOfGoodsVo.setGoodsList(goodsInBrandList);

            return listOfGoodsVo;

        }


        // Integer brandId = listOfGoodsBo.getBrandId();
        // if (brandId != 0) {
        //     List<Goods> goodsInBrand = goodsMapper.selectByBrandId(brandId);
        //
        //     List<GoodsOfFloorVo> goodsInBrandList = new ArrayList<>();
        //     for (Goods good : goodsInBrand) {
        //         GoodsOfFloorVo goodsListBean = new GoodsOfFloorVo(good.getId(), good.getName(), good.getBrief(), good.getPicUrl(), good.getIsNew(), good.getIsHot(), good.getCounterPrice(), good.getRetailPrice());
        //         goodsInBrandList.add(goodsListBean);
        //     }
        //     listOfGoodsVo.setGoodsList(goodsInBrandList);
        //
        //     // count
        //     int countGoodsInBrand = goodsInBrandList.size();
        //     listOfGoodsVo.setCount(countGoodsInBrand);
        // }


        return listOfGoodsVo;


    }
}
